﻿// View is a visual component that renders html and manipulates the dom
define([
    'Xjs/core/util',
    'Xjs/core/Composite',
    'Xjs/ui/HtmlRenderer',
    'Xjs/core/DomManipulator',
    'Xjs/core/ContentHolder'
],
function (util, Composite, HtmlRenderer, DomManipulator, ContentHolder) {
    'use strict';

    var type = 'view',
    View = Xjs.getType(type);

    if (View) { // It has been already loaded
        return View;
    }
    // It is the basic view unit
    // The view component can have view and attributes but it cannot have children components.
    // It can be bound to data through a binder the component must declare
    View = util.define({
        base: Composite,
        mixins: [
            HtmlRenderer,
            DomManipulator,
            ContentHolder
        ],
        construct: function (conf, parent) {

            View.base.constructor.call(this, conf, parent);

            HtmlRenderer.prototype.initialize.call(this, conf);
            DomManipulator.prototype.initialize.call(this, conf);
            ContentHolder.prototype.initialize.call(this, conf);

        },
        type: type,
        tag: 'div',
        border: false,

        // Whether to include the content as one of the children
        contentIncluded: true,

        ensureId: function () {
            View.base.ensureId.call(this);

            // Synchronize the id of the builder if needed
            if (this.builder) { // This method might be called before the builder is created
                this.builder.addAttributes({
                    id: this.id
                });
            }
        },

        onRender: function () {

            this.callHandlers('onRender'); // Call any handler registered for this event

            if (this.children) {
                this.children.forEach(function (c) {
                    c.onRender();
                });
            }

            this.rendered = true; // Flag it as rendered
        },

        // Destroyes this component and releases its resources
        destroy: function () {

            if (this.id) {
                this.off();  // Clear the events of this container
                this.remove(); // Remove the element from the DOM
            }

            View.base.destroy.call(this);
        }

    });

    Xjs.registerType(View);

    return View;
});